package controller;

import com.alibaba.fastjson2.JSONObject;
import model.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author lk
 * @create 2023-01-03 23:15
 */
@WebServlet("/team/updateUrl")
public class UpdateTeamUrlServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //文件上传
        String path = "/photo/team";
        String saveDir = getServletContext().getRealPath(path);

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        String url = null;

        try {
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                File file = new File(saveDir + "//" + new Date().getTime() + item.getName());
                item.write(file);
                url = req.getContextPath() + path + "//" + file.getName();
            }
        } catch (FileUploadException e) {
            System.out.println("文件上传异常：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //创建一个用来传数据的JSON对象
        JSONObject message = new JSONObject();
        message.put("url", url);
        resp.getWriter().write(message.toString());
    }
}
